<?php

declare(strict_types=1);

namespace app\middleware;

use app\common\service\LogService;
use think\Response;

class OperationLog
{
    protected LogService $logService;

    public function __construct(LogService $logService)
    {
        $this->logService = $logService;
    }

    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 设置扩展信息
        $extend = [
            'module' => app('http')->getName(),
            'controller' => $request->controller(),
            'action' => $request->action(),
            'user_agent' => $request->header('user-agent'),
        ];

        $this->logService->setExtend($extend);

        // 执行请求
        $response = $next($request);

        // 记录日志
        if ($response instanceof Response) {
            $result = $response->getData();
            $code = $result['code'] ?? 200;
            $errorMsg = $result['message'] ?? '';
            $this->logService->record($result, $code, $errorMsg);
        }

        return $response;
    }
}
